/**
 * Created by PiaoLiangDeWangRuoNan on 2018/9/30.
 */
import React from 'react';
import {connect} from 'react-redux';
import {Input, message, Button} from 'antd';
import {messages} from 'share/common';
import 'styles/login/find-password/found-password.scss';
import LoginService from 'containers/login/login.service';
import PasswordRule from 'components/template/reset-password/password-rule';
import ResetPasswordService from "components/template/reset-password/reset-password.service";
import ActiveAccountService from 'containers/login/components/account-login/active-account/active-account.service';
import 'styles/login/login-refactoring-ui.scss';

//默认的密码规则
const DefaultRule = {
  isNeedLowercase: true,
  isNeedNumber: true,
  isNeedSpecialChar: false,
  isNeedUppercase: false,
  maxLength: 32,
  minLength: 6
};

class FoundPassword extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rule: DefaultRule,
      imgLoading: false,//获取验证码的loading
      /*
      找回密码的步骤--
      login登录模块
      phoneEmail输入手机号邮箱模块
      confirmCode输入验证码模块
      newPassword输入新密码模块
      resetThenLogin点击完确认新密码页面渲染出的登录模块
      */
      step: "phoneEmail",//找回密码的步骤
      type: 'phone',//输入是手机号还是邮箱
      phoneNum: null,//输入的手机号或邮箱地址
      phoneCode: null,//获得的验证码
      firstPassword: null,//第一次输入的新密码
      secondPassword: null,//第二次输入的新密码
      codeTime: 60,//验证码倒数的时间
      copyInterval: null,
      src: "",//验证码图片路径
      attachmentOID: "",//验证码图片路径
      verifyCode: null,//输入的验证码
      loading: false,//button
    }
  }


  componentWillMount() {
    this.getVerifyCodeImage();
  }


  //获取验证码图片
  getVerifyCodeImage = () => {
    this.setState({
      imgLoading: true,
    });
    ActiveAccountService.getVerifyCodeImage().then(res => {
      let src = "data:image/png;base64," + res.data.image;
      this.setState({
        src: src,
        attachmentOID: res.data.attachmentOID,
        imgLoading: false,
      });
    }).catch(err => {
      this.setState({
        imgLoading: false,
      });
    })
  };

  backLogin = () => {
    clearInterval(this.state.copyInterval);
    this.setState({
      step: "login",
    });
    this.props.parentMessage("login");
  };

  //输入手机号或者邮箱时
  inputPhoneEmailChange = (e) => {
    this.setState({
      phoneNum: e.target.value,
      loading: false,
    });
  };

  //输入验证码时
  inputVerifyCodeChange = (e) => {
    this.setState({
      verifyCode: e.target.value,
      loading: false,
    });
  };

  //输完手机号点击下一步
  inputPhoneEmailNext = () => {
    const {phoneNum, attachmentOID, verifyCode} = this.state;
    let pass = LoginService.testPhoneOrEmail(phoneNum).pass;
    if(pass){
      this.setState({
        loading: true,
      });
      let type = LoginService.testPhoneOrEmail(phoneNum).type;
      LoginService.getConfirmCode(phoneNum, attachmentOID, verifyCode).then(
        res => {
          if (res.status === 200) {
            this.setState({
              step: "confirmCode",
              loading: false,
              type,
              codeTime: 60,
            }, () => {
              let copyInterval = setInterval(() => {
                let codeTime = this.state.codeTime;
                if (codeTime > 0) {
                  codeTime--;
                  this.setState({
                    codeTime,
                    copyInterval: copyInterval,
                  });
                }
                if (codeTime <= 0) {
                  clearInterval(copyInterval)
                }
              }, 1000);
            });
          }
        }
      ).catch(res => {
        this.getVerifyCodeImage();
        this.setState({
          loading: false,
        })
      });
    }
  };


  //输入验证码时
  enterConfirmCodeChange = (e) => {
    this.setState({
      phoneCode: e.target.value,
    });
  };

  //输完验证码点击下一步
  enterConfirmCodeNext = () => {
    this.setState({
      loading: true,
    });
    const {phoneNum, phoneCode} = this.state;
    LoginService.judgeConfirmCode(phoneNum, phoneCode).then(res => {
      this.setState({
        step: "newPassword",
        loading: false,
      });
      LoginService.getPasswordRule(phoneNum).then(res => {
        clearInterval(this.state.copyInterval);
        this.setState({
          rule: res.data,
          loading: false,
        })
      }).catch(res => {
        this.setState({
          loading: false,
        })
      })
    }).catch(res => {
      this.setState({
        loading: false,
      })
    })
  };

  //点击确认新密码
  confirmNewPassword = () => {
    const {phoneNum, phoneCode, firstPassword, secondPassword} = this.state;
    if (firstPassword !== secondPassword) {
      message.error(messages('login.key14'/*两次输入密码不相同*/));
      this.setState({
        firstPassword: '',
        secondPassword: '',
      })
    } else {
      if (ResetPasswordService.regPasswordByRule(secondPassword, this.state.rule)) {
        this.setState({
          loading: true,
        });
        LoginService.confirmNewPassword(phoneNum, phoneCode, secondPassword).then(res => {
          if (res.status === 200) {
            this.setState({
              step: "resetThenLogin",
              loading: false,
              firstPassword: '',
              secondPassword: '',
            });
            this.props.parentMessage("resetThenLogin", phoneNum)
          }
        }).catch(err => {
          this.setState({
            loading: false,
          });
        })
      }
    }
  };

  //第一次输入新密码时
  enterNewPasswordChange = (e) => {
    this.setState({
      firstPassword: e.target.value,
    })
  };
  //再次输入新密码时
  confirmNewPasswordChange = (e) => {
    this.setState({
      secondPassword: e.target.value,
    })
  };

  renderTitle = (text) => {
    return (
      <div className='module-title-text'>
        {text}
      </div>
    )
  };
  renderBackBtn = () => {
    return (
      <div className="back-login" onClick={this.backLogin}>
        {messages('login.key4'/*返回登录*/)}
      </div>
    )
  };
  //确认密码 step3
  enterNewPassword = () => {
    const {firstPassword, secondPassword, rule, loading} = this.state;
    return (
      <div>
        {this.renderTitle(messages('login.key53')/*创建新密码*/)}
          <PasswordRule rule={rule}/>
        <div className="inp-wrap" style={{marginTop: 0}}>
          <Input
            size="large"
            type="password"
            className={"enter-password-input"}
            value={firstPassword}
            placeholder={messages('login.key12'/*请输入新密码*/)}
            onChange={this.enterNewPasswordChange}/>
          <Input
            size="large"
            type="password"
            className={"enter-password-input"}
            value={secondPassword}
            placeholder={messages('login.key13'/*再次输入新密码*/)}
            onChange={this.confirmNewPasswordChange}/>
        </div>
          <Button type="primary"
                  size="large"
                  style={{width: "100%"}}
                  loading={loading}
                  className="login-refactoring-btn"
                  onClick={this.confirmNewPassword}>
            {messages('login.key20'/*确认新密码*/)}
          </Button>
        {this.renderBackBtn()}
      </div>
    )
  };
  //输入验证码这一步 step2
  enterConfirmCode = () => {
    const {codeTime, type, phoneNum, loading} = this.state;
    return (
      <div>
        {this.renderTitle(messages('login.key54')/*输入验证码*/)}
        <div dangerouslySetInnerHTML={{__html: messages('login.key55',{arg1:phoneNum,arg2:type})/*<span>已向您 {arg1} 的{arg2}发送验证码,请注意查收后在下方输入</span>*/}}
             className={"code-note"}/>
        <div className="inp-wrap">
          <div className="verify-code2">
            <Input size="large"
                   className="verify-code-inp"
                   style={{border: "none"}}
                   placeholder={messages('login.key8'/*请输入验证码*/)}
                   onChange={this.enterConfirmCodeChange}/>
            <div className="verify-code-img">
              {
                codeTime === 0 ?
                <span className="pointer get-message-code" onClick={this.inputPhoneEmailNext}>{messages('login.key9'/*重新获取*/)}</span>
                : <span className="get-message-code" style={{background: "#D2D2D2"}}>{codeTime}&nbsp;s</span>
              }
            </div>
            <div className="clear"/>
            <div className="login-refactoring-border"/>
          </div>
        </div>
          <Button type="primary"
                  size="large"
                  style={{width: "100%"}}
                  loading={loading}
                  className="login-refactoring-btn"
                  onClick={this.enterConfirmCodeNext}>
            {messages('login.key3'/*下一步*/)}
          </Button>
        {this.renderBackBtn()}
      </div>
    )
  };
  //step1
  enterAccount = () => {
    const {src, verifyCode, loading} = this.state;
    return (
      <div>
        {this.renderTitle(messages('login.key56')/*忘记密码？*/)}
        <div className="inp-wrap">
          <Input size="large"
                 className={"enter-password-input"}
                 placeholder={messages('login.key2'/*请输入手机号/邮箱*/)}
                 onChange={this.inputPhoneEmailChange}/>
          <div className="verify-code">
            <Input size="large"
                   className="verify-code-inp"
                   style={{border: "none"}}
                   placeholder={messages('login.key8'/*请输入验证码*/)}
                   onChange={this.inputVerifyCodeChange}/>
            <div className="verify-code-img">
              {
                src ? <img src={src}
                          onClick={this.getVerifyCodeImage}/>
                : <span onClick={this.getVerifyCodeImage}>{messages('setting.key1502'/*加载失败*/)}</span>
              }
            </div>
            <div className="clear"/>
            <div className="login-refactoring-border"/>
          </div>
        </div>
          <Button type="primary"
                  size="large"
                  className="login-refactoring-btn"
                  style={{width: "100%"}}
                  disabled={!verifyCode}
                  loading={loading}
                  onClick={this.inputPhoneEmailNext}>
            {messages('login.key3'/*下一步*/)}
          </Button>
        {this.renderBackBtn()}
      </div>
    )
  };

  renderEnter = () => {
    const {step} = this.state;
    if (step === "phoneEmail") {
      return this.enterAccount();
    }
    if (step === "confirmCode") {
      return this.enterConfirmCode();
    }
    if (step === "newPassword") {
      return this.enterNewPassword();
    }
  };

  render() {
    return (
      <div className="found-password-wrap login-refactoring-ui">
        {this.renderEnter()}
      </div>
    )
  }
}

FoundPassword.contextTypes = {
  router: React.PropTypes.object,
  parentMessage: React.PropTypes.func,  //传到 account-login 组件
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    tenant: state.login.tenant
  }
}

export default connect(mapStateToProps)(FoundPassword);

